<!--
 * @Description:告警规则编辑
 * @Author: 0001101008/HuYuxi
 * @Date: 2021-09-07 14:37:26
 * @LastEditTime: 2021-09-28 10:21:05
 * @LastEditors: 0001101008/HuYuxi
-->
<template>
  <div class="page-content" style="padding: 0">
    <div class="info">
      <h1 class="title">编辑告警规则</h1>
      <el-alert
        v-if="rulesForms.type === 'DISCARD'"
        title="过滤符合指定条件的告警。被过滤的告警会被直接丢弃，既不会显示在客户端界面上，也不会被存储。本规则仅对新上报的告警生效。"
        type="warning"
        show-icon
        class="alert-info"
      ></el-alert>
      <el-alert
        v-if="rulesForms.type === 'FILTER'"
        title="过滤符合指定条件的告警，被过滤的告警默认不会显示在客户端界面上，但可以通过告警查询功能查看。该规则不影响北向。"
        type="warning"
        show-icon
        class="alert-info"
      ></el-alert>
      <el-alert
        v-if="rulesForms.type === 'FORWARD'"
        title="告警前转规则可以在符合条件的告警上报时，将其通过邮件或者短信发送给指定人员。该规则不影响北向。"
        type="warning"
        show-icon
        class="alert-info"
      ></el-alert>
      <el-form
        ref="rulesForms"
        class="form"
        :model="rulesForms"
        :rules="rules"
        label-width="100px"
        label-position="right"
        width="500px"
      >
        <!-- 规则类型 -->
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item label="规则类型" prop="type">
              <el-select v-model="rulesForms.type" style="width:100%;">
                <el-option
                  v-for="(item, index) in ruleTypeList"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 名称 -->
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item
              label="名称"
              prop="name"
              :rules="{required: true, message: '请检查必填项！', trigger: 'blur'}"
            >
              <el-input v-model="rulesForms.name" placeholder="名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 条件时间 -->
        <el-row :gutter="20" type="flex" justify="start">
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item label="条件时间" prop="time">
              <el-date-picker
                v-model="rulesForms.startTime"
                type="datetime"
                placeholder="开始日期"
                format="yyyy-MM-dd HH:mm:ss"
                :picker-options="options"
                class="fl"
              ></el-date-picker>
              <el-date-picker
                v-model="rulesForms.endTime"
                type="datetime"
                placeholder="结束日期"
                format="yyyy-MM-dd HH:mm:ss"
                :picker-options="options"
                class="rt"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 网元类型 -->
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item label="网元类型" prop="neType">
              <el-select
                v-model="rulesForms.neType"
                style="width:100%;"
                clearable
                @change="changeNeType"
              >
                <el-option
                  v-for="(item, index) in neTypes"
                  :key="index"
                  :value="item.id"
                  :label="item.displayName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 状态 -->
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item label="状态" prop="state">
              <el-radio-group v-model="rulesForms.state">
                <el-radio label="ACTIVE">激活</el-radio>
                <el-radio label="SUSPEND">挂起</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="12">
            <!-- 描述 -->
            <el-form-item label="描述" prop="description">
              <el-input
                type="textarea"
                :rows="3"
                maxlength="200"
                show-word-limit
                v-model="rulesForms.description"
                placeholder="描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="12">
            <div v-if="rulesForms.type === 'FORWARD'">
              <!-- 联系人 -->
              <el-form-item
                label="联系人"
                prop="contacts"
                :rules="[
              {required: true, message: '请检查必填项！', trigger: 'change'}
              ]"
              >
                <el-select
                  v-model="rulesForms.contacts"
                  style="width:100%;"
                  v-paging="loadmore"
                  :filter-method="filterVmModel"
                  placeholder="请选择联系人"
                  filterable
                  clearable
                  @clear="filterVmModel"
                >
                  <el-option
                    v-for="(item, index) in contactsData"
                    :key="index"
                    :value="item.username"
                    :label="item.username"
                  ></el-option>
                </el-select>
              </el-form-item>
              <!-- 前转方式 -->
              <el-form-item label="前转方式" prop="forwardType">
                <el-radio-group v-model="rulesForms.forwardType">
                  <el-radio label="email">邮件地址</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <!-- 位置 -->
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item label="位置" prop="place">
              <el-switch v-model="rulesForms.place" @change="openPosition"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="24">
            <positionInfo
              :dataList="positionSelectList"
              @getPositionInfo="getPositionInfo"
              v-if="positionSelectList.length > 0"
            ></positionInfo>
          </el-col>
        </el-row>
        <!-- 告警码 -->
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item label="告警码" prop="alarmCode">
              <el-switch v-model="rulesForms.alarmCode" @change="openAlarmCode"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="24">
            <codeInfo
              :dataList="codeSelectList"
              @getCodeInfo="getCodeInfo"
              v-if="codeSelectList.length > 0"
            ></codeInfo>
          </el-col>
        </el-row>
      </el-form>
      <!-- 返回 创建-->
      <div class="marTop20">
        <el-button style="width: 90px" @click="cancel">返回</el-button>
        <el-button type="primary" style="width: 90px" @click="submitForm">更新</el-button>
      </div>
    </div>
    <alarmCode
      :diagStatus="diagStatus"
      :dataList="codeDataList"
      :selectedData="codeSelectedData"
      @closeAlarmCode="closeAlarmCode"
      @getSelectData="getSelectData"
    ></alarmCode>
    <position
      :diagPositionStatus="diagPositionStatus"
      :dataList="positionDataList"
      :selectedData="positionSelectedData"
      @closePosition="closePosition"
      @getPositionData="getPositionData"
    ></position>
  </div>
</template>
<script>
import dayjs from 'dayjs';
import alarmCode from './codeDiag.vue';
import codeInfo from './codeInfo';
import position from './positionDiag.vue';
import positionInfo from './positionInfo';
export default {
  components: { alarmCode, codeInfo, position, positionInfo },
  props: ['ruleInfo', 'codeDataList', 'neInfoList'],
  directives: {
    // 计算是否滚动到最下面
    'paging': {
      bind (el, binding) {
        // 获取element-ui定义好的scroll盒子
        const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
        SELECTWRAP_DOM.addEventListener('scroll', function() {
          // scrollHeight 获取元素内容高度(只读)
          // scrollTop 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
          // clientHeight 读取元素的可见高度(只读)
          // 如果元素滚动到底, 下面等式返回true, 没有则返回false:
          const condition = Math.round(this.scrollHeight - this.scrollTop) <= this.clientHeight;
          if (condition) {
            binding.value();
          }
        });
      }
    }
  },
  data () {
    return {
      ruleTypeList: [
        { value: 'DISCARD', label: '告警丢弃规则' },
        { value: 'FILTER', label: '告警过滤规则' },
        { value: 'FORWARD', label: '告警前转规则' }
      ],
      rulesForms: {
        type: 'FILTER',
        name: null,
        description: null,
        state: 'ACTIVE',
        contacts: null,
        forwardType: 'email',
        time: [],
        startTime: null,
        endTime: null,
        neType: null,
        position: {
          type: '',
          data: []
        },
        codes: [],
        createTime: null,
        creator: null,
      },
      // 联系人
      contactsData: [],
      // 网元类型
      neTypes: [],
      // 告警码数据
      // codeDataList: [],
      codeSelectedData: [],
      codeSelectList: [],
      diagStatus: false,
      // 网元位置数据
      positionDataList: [],
      positionSelectedData: [],
      positionSelectList: [],
      allNeList: [],
      someNeList: [],
      diagPositionStatus: false,
      options: {
        disabledDate (time) {
          let now = new Date().getTime() - 24 * 3600 * 1000;
          return time.getTime() < now;
        }
      },
      page: {
        page: 1,
        pageSize: 15,
        total: 0
      },
      // 是否可以进行分页
      filterText: '',
    };
  },
  watch: {
    'rulesForms.neType' (val) {
      this.handleNe(val);
    },
  },
  mounted () {
    let _this = this;
    _this.$nextTick(() => {
      _this.getContactList();
      _this.getNeTypeList();
      _this.getRowInfo(_this.ruleInfo);
    });
  },
  methods: {
    // 数组去重
    uniqueArr (arr, id) {
      if (arr.length === 0) {
        return;
      }
      for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          if (arr[i][id] === arr[j][id]) {
            arr.splice(j, 1);
            j--;
          }
        }
      }
      return arr;
    },
    // 获取编辑内容
    getRowInfo (val) {
      if (val) {
        this.rulesForms = {
          id: val.id,
          type: val.type,
          name: val.name,
          description: val.description,
          state: val.state,
          contacts: null,
          forwardType: 'email',
          time: [],
          startTime: val.startTime ? val.startTime.substring(0, 19) : null,
          endTime: val.endTime ? val.endTime.substring(0, 19) : null,
          neType: val.neType,
          position: {
            type: null,
            data: []
          },
          codes: val.codes,
          createTime: val.createTime ? val.createTime.substring(0, 19) : null,
          creator: val.creator
        };
        // 处理位置信息
        if (val.position && val.position.type) {
          let pList = [];
          this.rulesForms.position.type = val.position.type ? val.position.type : 'NE';
          this.rulesForms.position.data = val.position.data.length > 0 ? val.position.data : [];
          let pData = this.rulesForms.position.data;
          for (let i = 0, pLen = pData.length; i < pLen; i++) {
            for (let k = 0, len = this.neInfoList.length; k < len; k++) {
              if (pData[i] === this.neInfoList[k].id) {
                pList.push({
                  id: this.neInfoList[k].id,
                  label: this.neInfoList[k].label,
                  type: this.neInfoList[k].type,
                  disabled: false
                });
              }
            }
          }
          this.positionSelectList = pList;
          this.positionSelectedData = pList;
          if (this.positionSelectList.length > 0) {
            this.rulesForms.place = true;
          } else {
            this.rulesForms.place = false;
          }
        }
        if (!val.neType) {
          this.positionDataList = this.neInfoList;
        } else {
          this.positionDataList = this.neInfoList.filter(item => item.type === val.neType);
        }
        this.handleNe(val.neType);
        // 处理告警前转规则
        if (val.type === 'FORWARD') {
          this.rulesForms.contacts = val.attrs.contacts;
          this.rulesForms.forwardType = 'email';
        }
        // 过滤选中的告警码
        let list = [];
        for (let i = 0, len = val.codeTxt.length; i < len; i++) {
          for (let k = 0; k < val.codes.length; k++) {
            if (val.codeTxt[i].id === val.codes[k]) {
              list.push({
                id: val.codeTxt[i].id,
                label: val.codeTxt[i].label
              });
            }
          }
        }
        this.codeSelectList = [];
        this.codeSelectList = list;
        if (this.codeSelectList && this.codeSelectList.length > 0) {
          this.rulesForms.alarmCode = true;
        } else {
          this.rulesForms.alarmCode = false;
        }
      } else {
        this.$message.error('获取信息失败');
      }
    },
    // 获取联系人
    getContactList () {
      let _this = this;
      let params = {
        limit: _this.page.pageSize,
        offset: (_this.page.page - 1) * _this.page.pageSize
      };
      _this.$http.post({
        url: '/api/gateway/users/sdwan/nocachequery',
        data: params
      }).then(res => {
        let { status, resultBody } = res;
        if (status === '0') {
          _this.page.total = resultBody.count;
          _this.contactsData = resultBody.objects;
        }
      });
    },
    // 下拉框分页
    loadmore (isLoadMore) {
      let _this = this;
      let isPage = isLoadMore;
      // 筛选时不进行分页
      if (!_this.filterText) {
        if (isPage) {
          return;
        }
        _this.page.page++;
        let params = {
          limit: _this.page.pageSize,
          offset: (_this.page.page - 1) * _this.page.pageSize
        };
        _this.$http.post({
          url: '/api/gateway/users/sdwan/nocachequery',
          data: params
        }).then(res => {
          let { status, resultBody } = res;
          if (status === '0') {
            _this.page.total = resultBody.count;
            let list = resultBody.objects;
            _this.contactsData = _this.contactsData.concat(list);
            if (list.length === 0) {
              // 如果返回了空数组 则表示后面不存在数据此时不应该再进行分页
              isPage = true;
            }
          }
        });
      }
    },
    // 筛选方法
    filterVmModel (value) {
      let _this = this;
      _this.filterText = value;
      _this.rulesForms.contacts = value;
      // 筛选数据，有值时清空选项并按照关键字搜索对应结果集合
      if (value) {
        _this.$nextTick(() => {
          _this.page = {
            page: 1,
            pageSize: 15,
            total: 0
          };
          let params = {
            userName: _this.filterText,
            limit: _this.page.pageSize,
            offset: (_this.page.page - 1) * _this.page.pageSize
          };
          _this.$http.post({
            url: '/api/gateway/users/sdwan/nocachequery',
            data: params
          }).then(res => {
            let { status, resultBody } = res;
            if (status === '0') {
              _this.page.total = resultBody.count;
              _this.contactsData = resultBody.objects;
            }
          });
        });
      } else {
        // 空值时，触发重置
        _this.getContactList();
      }
    },
    // 获取类型信息
    getNeTypeList () {
      let _this = this;
      _this.$http.get({
        url: '/api/sdwan/resource/model/product',
      }).then(res => {
        let { status, resultBody } = res;
        if (status === '0') {
          _this.neTypes = resultBody.neTypes;
        } else {
          _this.$message.error('获取网元类型失败');
        }
      });
    },
    //  返回的回调
    cancel () {
      let _this = this;
      _this.$emit('returnBack', 1);
    },
    // 打开告警码
    openAlarmCode (val) {
      let _this = this;
      if (_this.codeSelectList.length > 0) {
        _this.rulesForms.alarmCode = true;
        if (!val) {
          _this.diagStatus = true;
        }
      } else {
        _this.rulesForms.alarmCode = false;
        _this.diagStatus = val;
      }
      _this.codeSelectedData = _this.codeSelectList;
    },
    // 打开告警码的回调
    closeAlarmCode (data) {
      let _this = this;
      _this.diagStatus = data;
    },
    // 选择告警码的回调
    getSelectData (data) {
      let _this = this;
      let codeData = JSON.parse(data);
      _this.rulesForms.codes = codeData;
      _this.diagStatus = false;
      // 过滤选中的告警码
      let list = [];
      let codeDataList = _this.codeDataList;
      for (let i = 0, len = codeDataList.length; i < len; i++) {
        for (let k = 0; k < codeData.length; k++) {
          if (codeDataList[i].id === codeData[k]) {
            list.push({
              id: codeDataList[i].id,
              label: codeDataList[i].label
            });
          }
        }
      }
      _this.codeSelectList = list.length > 0 ? _this.uniqueArr(list, 'id') : [];
      if (_this.codeSelectList && _this.codeSelectList.length > 0) {
        _this.rulesForms.alarmCode = true;
      } else {
        _this.rulesForms.alarmCode = false;
      }
    },
    // 告警码的表格删除回调
    getCodeInfo (data) {
      let _this = this;
      if (!data) {
        //  false 表示无数据
        _this.rulesForms.alarmCode = false;
      } else {
        // true 表示还有数据
        _this.rulesForms.alarmCode = true;
      }
    },
    // 打开位置
    openPosition (val) {
      let _this = this;
      if (_this.positionSelectList.length > 0) {
        _this.rulesForms.place = true;
        if (!val) {
          _this.diagPositionStatus = true;
        }
      } else {
        _this.rulesForms.place = false;
        _this.diagPositionStatus = val;
      }
      _this.positionSelectedData = _this.positionSelectList;
    },
    // 关闭位置的回调
    closePosition (data) {
      let _this = this;
      _this.positionSelectedData = [];
      _this.diagPositionStatus = data;
    },
    // 选择位置网元的回调
    getPositionData (data) {
      let _this = this;
      let pData = data.use;
      let notPData = data.notUse.length > 0 ? data.notUse : [];
      _this.diagPositionStatus = false;
      _this.rulesForms.position.data = pData;
      // 过滤选中的网元
      let list = [];
      for (let i = 0, len = _this.positionDataList.length; i < len; i++) {
        for (let k = 0; k < pData.length; k++) {
          if (_this.positionDataList[i].id === pData[k]) {
            list.push({
              id: _this.positionDataList[i].id,
              label: _this.positionDataList[i].label,
              disabled: false,
              type: _this.positionDataList[i].type
            });
          }
        }
      }
      _this.positionSelectList = list.concat(notPData);
      if (_this.positionSelectList.length > 0) {
        _this.rulesForms.place = true;
      } else {
        _this.rulesForms.place = false;
      }
    },
    // 网元表格的删除回调
    getPositionInfo (data) {
      let _this = this;
      if (!data) {
        //  false 表示无数据
        _this.rulesForms.place = false;
      } else {
        // true 表示还有数据
        _this.rulesForms.place = true;
      }
    },
    // 更改网元类型
    changeNeType (val) {
      let _this = this;
      _this.handleNe(val);
    },
    // 穿梭框网元能否点击处理
    handleNe (val) {
      let _this = this;
      if (!val) {
        // 查询所有的网元
        let list = _this.neInfoList;
        let sList = [];
        sList = _this.positionSelectedData;
        for (let k = 0; k < sList.length; k++) {
          _this.$set(sList[k], 'disabled', false);
        }
        _this.positionSelectedData = sList;
        _this.positionDataList = list;
      } else {
        // 过滤网元
        let list = _this.neInfoList.filter(item => item.type === val);
        let sList = [];
        sList = _this.positionSelectedData;
        for (let i = 0; i < list.length; i++) {
          for (let k = 0; k < sList.length; k++) {
            _this.$set(sList[k], 'disabled', false);
            if (list[i].type === sList[k].type) {
              _this.$set(sList[k], 'disabled', false);
            } else {
              _this.$set(sList[k], 'disabled', true);
            }
          }
        }
        _this.positionSelectedData = sList;
        _this.positionDataList = list;
      }
    },
    // 提交结果
    submitForm () {
      let _this = this;
      _this.$refs.rulesForms.validate(valid => {
        if (valid) {
          let params = {
            id: _this.rulesForms.id,
            type: _this.rulesForms.type,
            name: _this.rulesForms.name,
            description: _this.rulesForms.description,
            state: _this.rulesForms.state,
            neType: _this.rulesForms.neType,
            position: {
              type: '',
              data: []
            },
            codes: [],
            startTime: _this.rulesForms.startTime ? dayjs(_this.rulesForms.startTime).format('YYYY-MM-DD HH:mm:ss') + ' +08' : '',
            endTime: _this.rulesForms.endTime ? dayjs(_this.rulesForms.endTime).format('YYYY-MM-DD HH:mm:ss') + ' +08' : '',
            attrs: {},
            createTime: _this.rulesForms.createTime ? _this.rulesForms.createTime + ' +08' : '',
            creator: _this.rulesForms.creator,
            contacts: {}
          };
          // 位置传入
          if (_this.positionSelectList.length > 0) {
            let pList = [];
            _this.positionSelectList.map(item => {
              pList.push(item.id);
            });
            params.position['type'] = 'NE';
            params.position['data'] = pList;
          }
          // 告警码传入
          if (_this.codeSelectList.length > 0) {
            let codeList = [];
            _this.codeSelectList.map(item => {
              codeList.push(item.id);
            });
            params.codes = codeList;
          }
          if (_this.rulesForms.type === 'FORWARD') {
            params.attrs.contacts = _this.rulesForms.contacts;
            params.attrs.forwardType = _this.rulesForms.forwardType;
            let index = _this.contactsData.findIndex(item => item.username === _this.rulesForms.contacts);
            if (_this.rulesForms.forwardType === 'email') {
              if (_this.contactsData[index] && _this.contactsData[index].hasOwnProperty('email')) {
                params.contacts['email'] = this.contactsData[index].email ? this.contactsData[index].email : null;
              } else {
                _this.$message.error('此联系人的无邮件地址！');
                return;
              }
            }
          }
          _this.$http.put({
            url: '/api/fm/rule',
            data: params
          }).then(res => {
            if (res) {
              _this.$message.success('更新成功！');
              _this.cancel();
              _this.$parent.refresh();
              localStorage.removeItem('alarmRule');
            } else {
              _this.$message.error('更新失败！');
            }
          });
        } else {
          _this.$message.error('请检查必填项！');
        }
      });

    }
  }
};
</script>
<style lang="scss" scoped>
.info {
  .title {
    font-size: 22px;
    font-weight: 500;
    padding: 15px 40px;
    border-bottom: 1px solid #eee;
  }
  .alert-info {
    margin: 20px 0;
  }
}
.marTop20 {
  margin-top: 20px;
}
.fl {
  width: 48%;
  float: left;
}
.rt {
  width: 48%;
  float: right;
}
.page-bottom {
  padding: 10px 20px;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  border-top: 1px solid #dcdfe6;
}
@media only screen and (max-width: $device-phone) {
  .fl {
    width: 100%;
    float: left;
  }
  .rt {
    width: 100%;
    float: left;
    margin-top: 22px;
  }
  .page-bottom {
    width: 100%;
  }
}
</style>